package com.pkk.components.util.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: peikunkun
 * @create: 2018-10-25 18:19
 **/
public class QrCodeUtil {

  public QrCodeUtil() {
  }

  public BufferedImage GenerationQRCode(String content) throws WriterException {
    Map<EncodeHintType, Object> hints = new HashMap();
    hints.put(EncodeHintType.MARGIN, 0);
    BufferedImage image = null;
    BitMatrix bitMatrix = (new QRCodeWriter()).encode(content, BarcodeFormat.QR_CODE, 170, 170, hints);
    int width = bitMatrix.getWidth();
    int height = bitMatrix.getHeight();
    image = new BufferedImage(width, height, 2);

    for(int x = 0; x < width; ++x) {
      for(int y = 0; y < height; ++y) {
        image.setRGB(x, y, bitMatrix.get(x, y) ? Color.BLACK.getRGB() : Color.WHITE.getRGB());
      }
    }

    return image;
  }

  public BufferedImage GenerationQRCodeParams(String content, int qrcode_width, int qrcode_height) throws WriterException {
    Map<EncodeHintType, Object> hints = new HashMap();
    hints.put(EncodeHintType.MARGIN, 0);
    BufferedImage image = null;
    BitMatrix bitMatrix = (new QRCodeWriter()).encode(content, BarcodeFormat.QR_CODE, qrcode_width, qrcode_height, hints);
    int width = bitMatrix.getWidth();
    int height = bitMatrix.getHeight();
    image = new BufferedImage(width, height, 2);

    for(int x = 0; x < width; ++x) {
      for(int y = 0; y < height; ++y) {
        image.setRGB(x, y, bitMatrix.get(x, y) ? Color.BLACK.getRGB() : Color.WHITE.getRGB());
      }
    }

    return image;
  }
}
